# coding=utf-8

import string
import random, re

from web.utils import re_compile
from pyDes import *

__all__ = (
	'randstr', 'is_email', 'md5', 'cmp_i',
	'encrypt', 'decrypt',
)

# 随机字符串选取范围
_seeks = string.letters + '0123456789'
# TODO: 获取指定长度的随机字符串
def randstr(len = 10):
	return ''.join(random.choice(_seeks) for i in xrange(len))

# TODO: 判断制定字符串是否是正确的Email地址格式
def is_email(str):
	p = re_compile('^([a-z0-9_\.\-\+]+)@([\da-z\.\-]+)\.([a-z\.]{2,6})$', re.IGNORECASE)
	return p.match(str)

# TODO: md5加密给定字符串
def md5(src):
	if src:
		import hashlib
		m = hashlib.md5(src)
		return m.hexdigest()

	return None

# TODO: 忽略大小写比较两个字符串是否相等
def cmp_i(lhs, rhs):
	return cmp(lhs.lower(), rhs.lower())

# TODO: 获取des对象
def _des():
	return des('DESCRYPT', CBC, '\5\2\3\6\5\6\7\2', pad=None, padmode=PAD_PKCS5)

# TODO: 加密给定字符串
def encrypt(src):
	return src and _des().encrypt(src.encode('utf-8')) or None

# TODO: 解密给定字符串
def decrypt(src):
	try:
		return src and _des().decrypt(src).decode('utf-8') or None
	except:
		return None
